package de.pcsoft.framework.jclr;

import de.pcsoft.framework.jclr.exceptions.JCLRProcessException;

/**
 * User: Christoph
 * Date: 14.06.12
 * Time: 22:07
 */
class JCLRArgumentReadingUtils {

    static void scanForGroup(final String[] args, final GroupDefinitionType groupDefinitionType,
                                    final SettingsType settingsType, final JCLRResult result) throws JCLRProcessException {
        if (groupDefinitionType.isMixed()) {
            scanForGroupMixed(args, groupDefinitionType, settingsType, result);
        } else {
            scanForGroupOrdered(args, groupDefinitionType, settingsType, result);
        }
    }

    private static void scanForGroupMixed(final String[] args, final GroupDefinitionType groupDefinitionType,
                                          final SettingsType settingsType, final JCLRResult result) throws JCLRProcessException {
        for (String arg : args) {
            for (ArgumentType argumentType : groupDefinitionType.getSimpleArgumentAndValueArgumentAndStringArgument()) {
                handleArgument(argumentType, arg, result);
            }
        }
    }

    private static void scanForGroupOrdered(final String[] args, final GroupDefinitionType groupDefinitionType,
                                            final SettingsType settingsType, final JCLRResult result) throws JCLRProcessException {

        int counter = 0;
        for (ArgumentType argumentType : groupDefinitionType.getSimpleArgumentAndValueArgumentAndStringArgument()) {
            //No more args?
            if (args.length <= counter) {
                //Is optional argument?
                if (argumentType instanceof BasicArgumentType && ((BasicArgumentType) argumentType).isOptional()) {
                    continue; //Ignore argument
                } else {
                    //Throw error
                    result.setError(
                            new JCLRError(
                                    JCLRErrorType.MissingArgument,
                                    "Cannot find argument '" + argumentType.getKey() + "'!"
                            )
                    );
                    return;
                }
            }

            String arg = args[counter];
            handleArgument(argumentType, arg, result);

            counter++;
        }
    }

    private static void handleArgument(final ArgumentType argumentType, final String arg, final JCLRResult result) {
        if (argumentType instanceof StringArgumentType) {

        } else if (argumentType instanceof SimpleArgumentType) {

        } else if (argumentType instanceof ValueArgumentType) {

        } else if (argumentType instanceof KeyValueArgumentType) {

        } else
            throw new RuntimeException("Unknown argument type: " + argumentType.getClass().getName());
    }

}
